package com.xquant.marketdata.curvestrip.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xquant.common.security.utils.SecurityUtils;
import com.xquant.marketdata.curvestrip.domain.IrCurveSetDTO;
import com.xquant.marketdata.curvestrip.domain.IrCurveStripDTO;
import com.xquant.marketdata.curvestrip.entity.IrCurveDTO;
import com.xquant.marketdata.curvestrip.entity.TvolsurfaceRatesDTO;
import com.xquant.marketdata.curvestrip.service.IrCurveStripService;
import com.xquant.marketdata.utils.CommResponse;
import com.xquant.common.security.utils.ExcelUtil;
import com.xquant.common.core.web.controller.BaseController;
import com.xquant.common.core.web.page.TableDataInfo;
import com.xquant.common.log.annotation.Log;
import com.xquant.common.log.enums.BusinessType;
import com.xquant.marketdata.utils.DateUtils;
import com.xquant.marketdata.utils.ResponseVo;
import com.xquant.marketdata.utils.SysUtils;
import com.xquant.system.api.domain.SysUser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 下拉框查询
 *
 * @author ershuai.zhao
 */
@RestController
@RequestMapping("irCurveStrip")
public class IrCurveStripController extends BaseController {
    @Autowired
    private IrCurveStripService irCurveStripService;
    static String sm = "操作成功";

    /**
     * 利率曲线定义查询
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurveset:list')")
    @RequestMapping(value = "/queryIrCurveByPage.action")
    public TableDataInfo queryIrCurveByPage(@RequestParam Map<String, Object> param) {
        startPage();
        param.put("userId", SecurityUtils.getUserId());
        return getDataTable(irCurveStripService.queryIrCurveByPage(param));
    }

    /**
     * 查询贴现率&融资率曲线下拉列表
     */
    @RequestMapping(value = "/queryIrCurveCombox.action")
    public TableDataInfo queryIrCurveCombox(HttpServletRequest request) {
        Map<String, Object> params = new WeakHashMap<>();
        params.put("condition", request.getParameter("query"));
        if (StringUtils.isBlank(request.getParameter("query"))) {
            params.put("condition", request.getParameter("condition"));
        }
        params.put("userId", SecurityUtils.getUserId());
        return getDataTable(irCurveStripService.queryTirCurveCombox(params));
    }

    /**
     * 利率曲线定义查询导出
     */
    @Log(title = "利率信息", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurveset:export')")
    @RequestMapping(value = "/export")
    public void exportSet(HttpServletResponse response, @RequestParam Map<String, Object> param) {
        startPage();
        param.put("userId", SecurityUtils.getUserId());
        List<IrCurveSetDTO> list = irCurveStripService.queryIrCurveByPage(param);
        ExcelUtil<IrCurveSetDTO> util = new ExcelUtil<IrCurveSetDTO>(IrCurveSetDTO.class);
        util.exportExcel(response, list, "利率曲线定义");
    }

    /**
     * 利率曲线定义修改
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurveset:upt')")
    @RequestMapping(value = "/updateIrCurve.action")
    public CommResponse updateIrCurve(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        irCurveStripService.updateIrCurve(param);
        return new CommResponse(true, sm);
    }

    /**
     * 利率曲线定义新增
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurveset:add')")
    @RequestMapping(value = "/insertIrCurve.action")
    public CommResponse insertIrCurve(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        List<IrCurveSetDTO> list = irCurveStripService.checkIrCurve(param);
        if (list.size() >= 1) {
            return new CommResponse(false, "此利率曲线已存在，请删除后再新增");
        }
        irCurveStripService.allocateIrCurve(param);
        param.put("pipeId","-1");
        irCurveStripService.insertIrCurve(param);
        return new CommResponse(true, sm);
    }

    /**
     * 利率曲线定义删除
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurveset:del')")
    @RequestMapping(value = "/deleteIrCurve.action")
    public CommResponse deleteIrCurve(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        irCurveStripService.deleteIrCurve(param);
        return new CommResponse(true, sm);
    }

    /**
     * 查询 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/queryIrCurveRefSetByPage.action")
    public PageInfo<Map> queryIrCurveRefSetByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        PageInfo<Map> pageInfo = irCurveStripService.queryIrCurveRefSetByPage(param);
        return pageInfo;
    }

    /**
     * 查询曲线剥离列表
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurvestrip:export')")
    @RequestMapping(value = "/exportStrip.action")
    public void exportStrip(HttpServletResponse response, @RequestParam Map<String, Object> param) {
        List<IrCurveStripDTO> list = irCurveStripService.queryIrCurveRatesByPage(param);
        ExcelUtil<IrCurveStripDTO> util = new ExcelUtil<IrCurveStripDTO>(IrCurveStripDTO.class);
        util.exportExcel(response, list, "利率曲线剥离");
    }

    /**
     * 查询曲线剥离列表
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurvestrip:list')")
    @RequestMapping(value = "/queryIrCurveRatesListByPage.action")
    public TableDataInfo queryIrCurveRatesListByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        return getDataTable(irCurveStripService.queryIrCurveRatesByPage(param));
    }

    /**
     * 修改利率曲线剥离
     */
    @PreAuthorize("@ss.hasPermi('marketdata:irCurve:update')")
    @RequestMapping(value = "/updateIrCurveRates.action")
    public CommResponse updateIrCurveRates(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        irCurveStripService.updateIrCurveRates(param);
        return new CommResponse(true, sm);
    }

    /**
     * 新增利率曲线剥离
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurvestrip:add')")
    @RequestMapping(value = "/insertIrCurveRates.action")
    public CommResponse insertIrCurveRates(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        List<IrCurveStripDTO> list = irCurveStripService.queryIrCurveRatesByPage(param);
        if (list.size() >= 1) {
            return new CommResponse(false, "此曲线期限结构已存在，请删除后再新增!");
        }
        param.put("endDate", "2050-12-31");
        irCurveStripService.insertIrCurveRates(param);
        return new CommResponse(true, sm);
    }

    /**
     * 删除利率曲线剥离
     */
    @PreAuthorize("@ss.hasPermi('marketdata:irCurve:delete')")
    @RequestMapping(value = "/deleteIrCurveRates.action")
    public CommResponse deleteIrCurveRates(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        irCurveStripService.deleteIrCurveRates(param);
        return new CommResponse(true, sm);
    }

    /**
     * 查询利率曲线图形数据
     */
    @PreAuthorize("@ss.hasPermi('curve:ircurve:ircurvestrip:list')")
    @RequestMapping(value = "/queryIrCurveRatesByPage.action")
    public CommResponse queryIrCurveRatesByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        return new CommResponse(true, irCurveStripService.queryIrCurveRatesByPage(param));
    }

    /**
     * 查询 单条TIRCURVE
     */
    @RequestMapping(value = "/getIrCurveMx.action")
    public CommResponse getIrCurveMx(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        List<Map> list = irCurveStripService.getIrCurveMx(param);
        if (list.isEmpty()) {
            return new CommResponse(true);
        }
        return new CommResponse(true, list.get(0));
    }

    /**
     * 修改 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/updateIrCurveRefSet.action")
    public CommResponse updateIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        int ct = irCurveStripService.queryIrCurveRefSetByDate(param);
        irCurveStripService.deleteIrCurveRefSetByDate(param);
        irCurveStripService.updateIrCurveRefSet(param);
        param.put("endDate", "2050-12-31");
        irCurveStripService.insertIrCurveRefSetByDate(param);
        return new CommResponse(true, sm);
    }

    /**
     * 新增 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/insertIrCurveRefSet.action")
    public CommResponse insertIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        List<Map> list = irCurveStripService.queryIrCurveRefSetByPage(param).getList();
        if (list.size() >= 1) {
            return new CommResponse(false, "此样本点已存在，请删除后再新增!");
        }
        param.put("endDate", "2050-12-31");
        irCurveStripService.insertIrCurveRefSet(param);
        return new CommResponse(true, sm);
    }

    /**
     * 删除 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/deleteIrCurveRefSet.action")
    public CommResponse deleteIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());

        irCurveStripService.deleteIrCurveRefSet(param);
        return new CommResponse(true, sm);
    }


    /**
     * 过滤样本点 TIRCURVE_REF_SET
     * todo
     */

    @RequestMapping(value = "/resetIrCurveRefSet.action")
    public CommResponse resetIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        //irCurveStripService.deleteAllIrCurveRefSet(param);
        //irCurveStripService.filterIrCurveRefSet(param);
        PageInfo<Map> pageInfo = irCurveStripService.queryFilterIrCurveRefSetByPage(param);
        return new CommResponse(true, pageInfo);
    }

    /**
     * 过滤样本点 TIRCURVE_REF_SET
     * todo
     */

    @RequestMapping(value = "/queryFilterIrCurveRefSetByPage.action")
    public PageInfo<Map> queryFilterIrCurveRefSetByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        JSONObject jsonObject = JSON.parseObject(param.get("filter").toString());
        param.put("aType", jsonObject.getString("aType"));
        PageInfo<Map> pageInfo = irCurveStripService.queryFilterIrCurveRefSetByPage(param);
        return pageInfo;
    }

    @GetMapping("/getByIrcCode.action")
    public CommResponse getByIrcCode(@RequestParam Map<String, Object> param) throws Exception
    {
        Boolean flag = false;
        String ircCode = (String) param.get("ircCode");
        IrCurveSetDTO one = irCurveStripService.getByIrcCode(ircCode);
        if (one == null) {
            flag = true;
        }
        return new CommResponse(true,flag);
    }

    @PreAuthorize("@ss.hasPermi('marketdata:irCurve:import')")
    @PostMapping("/importIrCurve")
    public CommResponse importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<IrCurveDTO> util = new ExcelUtil<IrCurveDTO>(IrCurveDTO.class);
        Map<String,Object> importResultMap = util.importExcel(file.getInputStream());
        List<IrCurveDTO> list = (List<IrCurveDTO>) importResultMap.get("list");
        HashMap<String, Set<String>> map = new HashMap<>();
        HashSet<String> set = new HashSet<>();
        list.stream().forEach(irCurveDTO->{
            irCurveDTO.setFwdStartTerm("0D");
            set.add(irCurveDTO.getIrcCode());
        });
        list.stream().forEach(irCurveDTO->{
            if(set.contains(irCurveDTO.getIrcCode())){
                if (map.get(irCurveDTO.getIrcCode())==null) {
                    map.put(irCurveDTO.getIrcCode(),new HashSet<String>());
                }
                map.get(irCurveDTO.getIrcCode()).add(irCurveDTO.getBegDate());
            }
        });
        irCurveStripService.deleteIrCurveList(map);
        list = irCurveStripService.getLastIrCurve(map, list);
        boolean flag = irCurveStripService.insertIrCurveList(list);
        if (!flag) {
            return CommResponse.success("导入失败");
        }
        return CommResponse.success("导入成功");
    }

    @PreAuthorize("@ss.hasPermi('marketdata:irCurve:add')")
    @PostMapping(value = "/addIrCurveRatesDTO.action")
    public CommResponse addIrCurve(@RequestBody IrCurveDTO form)
    {
        form.setImpTime(DateUtils.getCurr_YYYY_MM_DD_HH_MM_SS());
        boolean flag = irCurveStripService.insertIrCurve2(form);
        return CommResponse.success();

    }

    /**
     * 下载文件
     */
    @RequestMapping(value = "/downloadFile.action")
    @PreAuthorize("@ss.hasPermi('marketdata:Curve:download')")
    public void downloadFile(HttpServletResponse response, @RequestParam  Map  param) throws UnsupportedEncodingException {
        try {
            String fileName=param.get("fileName").toString();
            String businType=param.get("businType").toString();
            //为文件名解码
            fileName = SysUtils.decode(fileName);
            fileName = fileName.replace("%20", " ");
//            String fullFilePath = new ClassPathResource("templates/simpleTemplate.xlsx").getFile().getPath();
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = null;
            switch (businType) {
                case "Ircurve":
                    resources = resolver.getResources("templates/IrCurve.xlsx");
                    break;
                case "DivIrcurve":
                    resources = resolver.getResources("templates/DivIrCurve.xlsx");
                    break;
                case "Volatility":
                    resources = resolver.getResources("templates/VolatilityCurve.xlsx");
                    break;
            }
            final InputStream inputStream = resources[0].getInputStream();
            File file = File.createTempFile(fileName, ".xls");
            try {
                FileUtils.copyInputStreamToFile(inputStream, file);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
            response = SysUtils.downloadFile(response, file.getPath(), fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/updateCurveUserAuthority.action")
    @PreAuthorize("@ss.hasPermi('curve:ircurve:allocate')")
    public Object updateCurveUserAuthority(@RequestBody Map<String, Object> params) {
        irCurveStripService.updateCurveUserAuthority(params);
        return CommResponse.success("修改成功");
    }


}
